/**
* Tero Paananen
* tepaanan@gmail.com
* FINLAND
*/

#include "serversocket.h"

ServerSocket::ServerSocket(QObject *parent) :
    QObject(parent)
{
    iServerMode = true;
    iUdpBroadcastSocket = 0;
    iWantedToStart = false;
    QTimer::singleShot(2000,this,SLOT(startNetwork()));
}


void ServerSocket::startNetwork()
{
    iNetworkManager = new QNetworkConfigurationManager(this);
    QNetworkConfiguration cfg = iNetworkManager->defaultConfiguration();
    iNetworkSession = new QNetworkSession(cfg,this);
    iNetworkSession->open();
    writeLog("Opening network...");
    iNetworkSession->waitForOpened();
    writeLog("Network open");
    if (iWantedToStart) {
        writeLog("Delayed start");
        start();
    }
}

ServerSocket::~ServerSocket()
{
    stop();
}


void ServerSocket::enableServerMode()
{
    writeLog("SERVER mode");
    iServerMode = true;
}

void ServerSocket::enableClientMode()
{
    writeLog("CLIENT mode");
    iServerMode = false;
}

void ServerSocket::start()
{
    writeLog("Try to start Server");
    if (!iNetworkSession) {
        // Network not open. Open later when network exists at networkUpdated()
        writeLog("Waiting for network...");
        iWantedToStart = true;
        return;
    }

    if (!iUdpBroadcastSocket) {
        iUdpBroadcastSocket = new QUdpSocket(this);
        if (!iServerMode) {
            QObject::connect(iUdpBroadcastSocket, SIGNAL(readyRead()),this, SLOT(udpGetData()));
        }
        writeLog("Started");
    }
    iWantedToStart = false;
}


void ServerSocket::stop()
{
    if (iUdpBroadcastSocket) {
        iUdpBroadcastSocket->close();
        iUdpBroadcastSocket = 0;
    }

    if (iNetworkSession) {
        iNetworkSession->close();
        iNetworkSession = 0;
    }
}

void ServerSocket::writeLog(QString log)
{
    log = log.prepend("[Udp Server] ");
    //qDebug() << log;
    emit serverLog(log);
}

void ServerSocket::udpGetData()
{
    while (iUdpBroadcastSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(iUdpBroadcastSocket->pendingDatagramSize());
        iUdpBroadcastSocket->readDatagram(datagram.data(), datagram.size());

        if (datagram.startsWith(SERVER_ID)) {
            QString data(datagram);
            writeLog("From server UDP: "+data);
        }
        break;
    }
}

void ServerSocket::sendToClient(QString msg)
{
    if (iUdpBroadcastSocket) {
        QByteArray datagram;
        datagram.append(QString(SERVER_ID));
        datagram.append(msg);
        iUdpBroadcastSocket->writeDatagram(datagram.data(), datagram.size(),
                                           QHostAddress::Broadcast, SERVER_PORT);
        writeLog("To Client: "+msg);
    }
}
